const path = require('path');
const myUnit = require('../../express/bin/unit/myUnit.js');
const multer = require('multer');
let myMulterStorage = require('../../express/bin/unit/myMulterStorage.js');

let upload_text_control = function (app,rootDir) {
    let uri = rootDir+'/textUpload/:userName';
    app.use(uri,function (req,res,next) {

        let _path;
        let articleUpload;
        try{
            _path = req.params.userName;
            articleUpload =
                multer({storage: myMulterStorage.storage('../article/'+_path)});
        }catch(err){
            console.error('position:upload_text_control.js->'+uri);
            console.error(err);
        }

        app.post(uri,articleUpload.single('myForm'),function (req,res) {
            /*
            * 负责接收表单上传的文本文件,如果数据库中不存在该文件,则将其地址编码后传入数据库中
            * 如果数据库中已有该文件,则只更新文件内容(更新文件内容这部分由multer完成,其代码并不在这个中间件内)
            * */
            try{
                let article_title = path.parse(req.file.filename).name;
                let article_address = myUnit.myCrypto.strEncode(path.resolve(req.file.path));
                let author = 'coffeeCat';

                let dbName = 'article_db';
                let tableName = 'article_table';
                let columnName =
                    'article_title,' +
                    'article_address';
                let condition = [];
                condition.push('article_title='+'\''+article_title+'\'');

                myUnit.myDB.sql.query(dbName,tableName,columnName,condition,function (err, results, fields) {
                    if(results[0]===undefined){
                        let columnName =
                            'article_title,' +
                            'article_address,' +
                            'author';
                        let columnValue = [];
                        columnValue.push(article_title);
                        columnValue.push(article_address);
                        columnValue.push(author);
                        myUnit.myDB.sql.insert(dbName,tableName,columnName,columnValue);
                    }
                });
            }catch(err){
                console.error('position:upload_text_control.js->'+uri);
                console.error(err);
            }
            res.send('ok');
        });

        next();
    });


};

module.exports = upload_text_control;